package com.gcb.framework.security.filter;

import com.gcb.framework.model.AppLoginUser;
import com.gcb.framework.model.LoginUser;
import com.gcb.framework.utils.SecurityUtils;
import com.gcb.common.utils.StringUtils;
import com.gcb.framework.security.handle.AuthTouristTokenUtils;
import com.gcb.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器 验证token有效性
 *
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private AuthTouristTokenUtils AuthTouristTokenUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

         //游客token过滤
        AuthTouristTokenUtils.authTouristToken(request);

        LoginUser loginUser = tokenService.getLoginUser(request);
        AppLoginUser appUser = tokenService.getAppLoginUser(request);
        if (StringUtils.isNotNull(loginUser)){// 是运营商或渠道商登录
            if (StringUtils.isNull(SecurityUtils.getAuthentication())) {
                tokenService.verifyToken(loginUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        } else if (StringUtils.isNotNull(appUser)){// 是企业客户登录
            if (StringUtils.isNull(SecurityUtils.getAuthentication())) {
                tokenService.verifyToken(appUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(appUser, null, appUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        } else if (StringUtils.isNotNull(loginUser) && StringUtils.isNotNull(appUser)){
            throw new ServletException("用户登录异常");
        } else {}

        chain.doFilter(request, response);
    }
}
